package com.example.client_first;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 当client向server注册时，它会提供一些元数据，例如主机和端口，URL，主页等。Eureka server 从每个client实例接收心跳消息。
 * 如果心跳超时，则通常将该实例从注册server中删除。
 */
@EnableEurekaClient
@EnableDiscoveryClient
@SpringBootApplication
@RestController
// 开启断路器
@EnableHystrix
// 开启hystrixDashboard
@EnableHystrixDashboard
@EnableCircuitBreaker
public class ClientFirstApplication {

    /**
     * 访问地址 http://localhost:8762/actuator/hystrix.stream
     * 可视化界面 localhost:8762/hystri
     *  在界面依次输入：http://localhost:8762/actuator/hystrix.stream 、2000 、miya
     *  点确定。
     * @param args
     */

    public static void main(String[] args) {
        SpringApplication.run(ClientFirstApplication.class, args);
    }


    @Value("${server.port}")
    String port;

    @RequestMapping("/hi")
    @HystrixCommand(fallbackMethod = "hiError")
    public String home(@RequestParam(value = "name", defaultValue = "默认名称") String name) {
        return "hi " + name + " ,i am from port:" + port;
    }


    public String hiError(String name) {
        return "hi," + name + ",sorry,error!";
    }

    @Bean
    public ServletRegistrationBean getServlet(){

        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();

        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);

        registrationBean.setLoadOnStartup(1);

        registrationBean.addUrlMappings("/actuator/hystrix.stream");

        registrationBean.setName("HystrixMetricsStreamServlet");


        return registrationBean;
    }
}

